package com.wzt.controller;

import com.wzt.service.ChatAssistant;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.model.StreamingResponseHandler;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.concurrent.TimeUnit;



@RestController
@Slf4j
public class ChatLanguageModelController
{
    @Resource
    private StreamingChatLanguageModel streamingChatLanguageModel;
    @Resource
    private ChatAssistant chatAssistant;


    //1
    @GetMapping(value = "/chatstream/chat2")//接收请求
    public Flux<String> chat2(@RequestParam("prompt") String prompt, HttpServletResponse response) {
        // 设置响应的字符编码
        response.setCharacterEncoding("UTF-8");

        //调用流式聊天服务 返回一个Flux<String>，表示一系列异步生成的字符串。
        chatAssistant.chat2(prompt).subscribe(
                System.out::println,  // onNext  这里的代码会在每次有新的String时执行
                Throwable::printStackTrace,  // onError 这里的代码会在发生错误时执行
                () -> System.out.println("onComplete")  // onComplete 这里的代码会在Flux(流)完成时执行
        );

        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(7); } catch (InterruptedException e) { e.printStackTrace(); }

        return chatAssistant.chat2(prompt);
    }

    //2
    @GetMapping(value = "/chatstream/assistant2")
    public void assistant2(@RequestParam(value = "prompt", defaultValue = "hello, 北京有什么好吃的？") String prompt)
    {
        //.generate(prompt, handler) prompt：用户输入的提示。 handler：自定义的 StreamingResponseHandler<AiMessage> 实现，用于处理生成的令牌
        streamingChatLanguageModel.generate(prompt, new StreamingResponseHandler<AiMessage>(){
            @Override
            public void onNext(String token) {
                System.out.println(token);
            }

            @Override
            public void onError(Throwable error) {

            }
        });
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
    }
}

